package health.lm.com.home.fragment;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.androidkun.xtablayout.XTabLayout;
import com.blankj.rxbus.RxBus;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lm.sjy.titlebar.widget.CommonTitleBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import health.lm.com.component_base.base.adapter.BaseFragmentStateAdapter;
import health.lm.com.component_base.base.event.BusProvider;
import health.lm.com.component_base.base.event.IBus;
import health.lm.com.component_base.base.mvp.fragment.XLazyFragment;
import health.lm.com.component_base.scan.ScanUtil;
import health.lm.com.component_base.widget.SuperDividerItemDecoration;
import health.lm.com.data.HttpCST;
import health.lm.com.home.R;
import health.lm.com.home.R2;
import health.lm.com.home.adapter.HomeFragmentAdapter;
import health.lm.com.home.adapter.HomePageAdapter;
import health.lm.com.home.entity.HomeMultiEntity;
import health.lm.com.home.entity.HomePageEntity;
import health.lm.com.home.presenter.HomePresenter;
import health.lm.com.router.ARouterConstant;

/**
 * 首页
 *
 * @author GQI
 */
@Route(path = ARouterConstant.HomeFragment)
public class HomeFragment extends XLazyFragment<HomePresenter> implements BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;
    @BindView(R2.id.title_bar)
    CommonTitleBar mTitleBar;
    @BindView(R2.id.tabLayout)
    TabLayout mTabLayout;
    @BindView(R2.id.xTablayout)
    XTabLayout mXTablayout;
    @BindView(R2.id.appbar)
    AppBarLayout mAppbar;
    @BindView(R2.id.viewpager)
    ViewPager mViewpager;
    @BindView(R2.id.rv_data)
    RecyclerView mRvData;
    private HomeFragmentAdapter mFragmentAdapter;
    private HomePageAdapter mPageAdapter;
    //二级菜单列表
    private List<HomeMultiEntity.Title.TagData> mSecondTag = new ArrayList<>();
    private List<String> secondTitle = new ArrayList<>();

    //首页下部分列表是否刷新的表示，处理每次点击详情后返回刷新跳到第一次新闻问题
    private int type = 1;

    //一级菜单
    private String AMenuId;
    private boolean isRefresh = false;
    //是否已经初始化了ViewPagerAdapter
    private boolean isInitViewPager = false;

    @Override
    public void initData(Bundle savedInstanceState) {
        mXTablayout.setxTabDisplayNum(5);
        mFragmentAdapter = new HomeFragmentAdapter(new ArrayList<>());
        setTitleBar();
        mRvData.setLayoutManager(new LinearLayoutManager(context));
        mRvData.addItemDecoration(new SuperDividerItemDecoration(new SuperDividerItemDecoration.Builder(context)));
        //initDataAdapter();
        //getP().getData(type);
        //getP().notice();
        BusProvider.getBus().subscribe(this, new RxBus.Callback<IBus.AbsEvent>() {
            @Override
            public void onEvent(IBus.AbsEvent pAbsEvent) {
                if (pAbsEvent.getTag() == 1000) {
                    mAppbar.setExpanded(true);
                }
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_animation_home;
    }

    @Override
    public HomePresenter newP() {
        return new HomePresenter();
    }

    /**
     * 设置通知数量
     *
     * @param noticeNum
     */
    public void setNoticeNum(int noticeNum) {
        if (noticeNum == 0) {
            mTitleBar.getRightImageButton().setImageDrawable(ContextCompat.getDrawable(context, R.drawable.home_nav_icon_message));
        } else {
            mTitleBar.getRightImageButton().setImageDrawable(ContextCompat.getDrawable(context, R.drawable.home_nav_icon_message2));
        }
    }

    private void setTitleBar() {
        mTitleBar.getCenterTextView().setText("首页");
        mTitleBar.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
        mTitleBar.getLeftImageButton().setImageDrawable(ContextCompat.getDrawable(context, R.drawable.home_nav_icon_scan));
        mTitleBar.getRightImageButton().setImageDrawable(ContextCompat.getDrawable(context, R.drawable.home_nav_icon_message));
        mTitleBar.setListener((v, action, extra) -> {
            switch (action) {
                case CommonTitleBar.ACTION_LEFT_BUTTON:
                    //getvDelegate().toastLong("二维码扫描");
                    ScanUtil.getInstance().homeNavScan(context, result -> {
                    });
                    break;
                case CommonTitleBar.ACTION_RIGHT_BUTTON:
                    gotoActivity(ARouterConstant.NoticesActivity);
                    //getvDelegate().toastLong("消息");
                    break;
            }
        });
    }

    /**
     * 设置数据
     */
    public void setData(List<HomeMultiEntity> pData) {
        mRvList.setLayoutManager(new LinearLayoutManager(context));
        mFragmentAdapter.setNewData(pData);
        mRvList.setAdapter(mFragmentAdapter);
    }

    public void setTitleData(List<HomeMultiEntity.Title> pTitleData) {
        type = 0;
        if (pTitleData.size() <= 0) return;
        mTabLayout.removeAllTabs();
        for (HomeMultiEntity.Title title : pTitleData) {
            mTabLayout.addTab(mTabLayout.newTab().setText(title.getName() + ""));
        }

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //清空数据
                //mPageAdapter.getData().clear();
                //mPageAdapter.notifyDataSetChanged();
                //一级菜单ID
                AMenuId = pTitleData.get(tab.getPosition()).getId();
                //initDataAdapter();

                mSecondTag.clear();
                secondTitle.clear();
                //page = 1;
                //isRefresh = true;
                for (HomeMultiEntity.Title.TagData tagData : pTitleData.get(tab.getPosition()).getTag()) {
                    mSecondTag.add(tagData);
                    secondTitle.add(tagData.getTag());
                }

                List<Fragment> fragments = new ArrayList<>();
                List<String> ids = new ArrayList<>();
                for (HomeMultiEntity.Title.TagData tagData : pTitleData.get(tab.getPosition()).getTag()) {
                    fragments.add(HomePageFragment.getInstance(tagData.getId(), AMenuId));
                    ids.add(tagData.getTag());
                }
                initPagerAdapter(fragments, ids);
                //           mXTablayout.removeAllTabs();
                //           if (mSecondTag.size() <= 0) {
                //               mXTablayout.setVisibility(View.GONE);
                //               return;
                //           } else mXTablayout.setVisibility(View.VISIBLE);

                //           for (HomeMultiEntity.Title.TagData tagData : mSecondTag) {
                //               mXTablayout.addTab(mXTablayout.newTab().setText(tagData.getTag()));
                //           }
                //type 2 表示视频资讯
                //setViewPager(pTitleData.get(tab.getPosition()).getId());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //    mXTablayout.setOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
        //        @Override
        //        public void onTabSelected(XTabLayout.Tab tab) {
        //            page = 1;
        //            isRefresh = true;
        //            HomeMultiEntity.Title.TagData tagData = mSecondTag.get(tab.getPosition());
        //            //二级菜单ID
        //            BMenuId = tagData.getId();
        //            getP().getData(tagData.getId(), page, pageSize);
        //            mRvData.scrollToPosition(0);
        //        }

        //        @Override
        //        public void onTabUnselected(XTabLayout.Tab tab) {

        //        }

        //        @Override
        //        public void onTabReselected(XTabLayout.Tab tab) {

        //        }
        //    });

        //第一次默认
        Objects.requireNonNull(mTabLayout.getTabAt(0)).select();
        List<Fragment> fragments = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        for (HomeMultiEntity.Title.TagData tagData : pTitleData.get(0).getTag()) {
            mSecondTag.add(tagData);
            secondTitle.add(tagData.getTag());
            fragments.add(HomePageFragment.getInstance(tagData.getId(), AMenuId));
            ids.add(tagData.getTag());
        }
        initPagerAdapter(fragments, ids);
        //mXTablayout.setxTabDisplayNum(mSecondTag.size());
        //    for (HomeMultiEntity.Title.TagData tagData : pTitleData.get(0).getTag()) {
        //        mXTablayout.addTab(mXTablayout.newTab().setText(tagData.getTag()));
        //    }
        //    Objects.requireNonNull(mXTablayout.getTabAt(0)).select();
        //getP().getData(pTitleData.get(0).getId(), page, pageSize);
    }

    @Deprecated
    private void initDataAdapter() {
        //AMenuId 2 视频新闻，其他 图文新闻
        if ("2".equals(AMenuId)) mPageAdapter = new HomePageAdapter(new ArrayList<>(), 2);
        else mPageAdapter = new HomePageAdapter(new ArrayList<>());
        mPageAdapter.setOnLoadMoreListener(this, mRvList);
        mPageAdapter.setEnableLoadMore(true);
        mRvData.setAdapter(mPageAdapter);

        mPageAdapter.setOnItemClickListener((adapter, view, position) -> {
            HomePageEntity pageEntity = (HomePageEntity) adapter.getData().get(position);
            //点击跳转新闻详情
            ARouter.getInstance().build(ARouterConstant.JSWebActivity)
                    .withString("url", pageEntity.getJump_url())
                    .withString(HttpCST.SHARE_URL, pageEntity.getJump_url())
                    .navigation();
        });
    }

    /**
     * viewpager Adapter
     */
    private void initPagerAdapter(List<Fragment> fragmentList, List<String> mTitles) {
        //if (isInitViewPager) return;
        isInitViewPager = true;
        BaseFragmentStateAdapter stateAdapter = new BaseFragmentStateAdapter(getFragmentManager(), fragmentList, mTitles);
        //mViewpager.setOffscreenPageLimit(3);
        mViewpager.setAdapter(stateAdapter);
        mXTablayout.setupWithViewPager(mViewpager);
    }

    @Deprecated
    public void setNewData(List<HomePageEntity> pNewData) {
        if (null == mPageAdapter) return;
        if (isRefresh) {
            mPageAdapter.setNewData(pNewData);
            isRefresh = false;
        } else {
            mPageAdapter.addData(pNewData);
            int pageSize = 10;
            if (pNewData.size() <= pageSize) mPageAdapter.loadMoreEnd();
            else {
                mPageAdapter.loadMoreComplete();
            }
        }
        if (mPageAdapter.getData().size() <= 0) mPageAdapter.setEmptyView(empty());
        mPageAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadMoreRequested() {
        //page++;
        //getP().getData(BMenuId, page, pageSize);
    }

    @Override
    protected void onResumeLazy() {
        super.onResumeLazy();
        //isRefresh = true;
        //page = 1;
        //if (null != mPageAdapter) mRvData.setAdapter(mPageAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        //isRefresh = true;
        //page = 1;
        getP().getData(type);
    }

    @Override
    public boolean useEventBus() {
        return true;
    }
}
